<template>
    <el-dialog v-if="dialogVisible" :close-on-click-modal='false' title="上传视频" :visible.sync="dialogVisible" @close="resetForm('addVideoSzRef')" width="520px" custom-class="upload_dia">
        <div class="flexbox flexcenter up_header">
            <div class="flexbox flexcenter"> 
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none">
                    <rect width="20" height="20" rx="10" fill="#009F26"/>
                    <path d="M7.5 10.8333L9.26441 12.2449C9.44157 12.3866 9.69956 12.3605 9.8448 12.1862L13.75 7.5" stroke="white" stroke-width="1.66667" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div> 
            <div>确认信息</div>
             <div class="line"></div>  
             <div>2</div>
             <div>上传成片文件</div>
      </div>
        <el-form label-position="top" label-width="auto" size="medium" :hide-required-asterisk='true' :model="addVideoSzForm" :rules="addVideoSzRules" ref="addVideoSzRef">
            <el-form-item prop="material">
                <div class="pot_content flexbox flexcenter" v-if="videoUrl">
                    <div class="video_box">
                        <img src="../../../assets/img/del_icon3.svg" alt="" class="delet_icon" @click="deletVideo">
                        <img :src="videoUrl+'&x-oss-process=video/snapshot,t_0,f_jpg'" alt="" width="109" height="181">
                    </div>
                </div>
                <el-upload class="load-uploader" drag :show-file-list="false" accept=".MP4,.mp4" :disabled="upload_disabled" action :http-request="videoUploadRequest" :before-upload="beforeVideoUpload" v-else>
                    <div class="pot_content flexbox flexcenter">
                        <el-progress type="circle" :percentage="progress_val" v-if="disVideo"></el-progress>
                        <template v-else>
                            <img src="../../../assets/img/pot_video.svg" alt="">
                            <span class="pot_text">点击上传 或直接将视频文件拖入此区域</span>
                            <span class="pot_tips">视频大小不超过 100MB，视频格式为 MP4</span>
                        </template>
                    </div>
                </el-upload>
            </el-form-item>
            <!-- <el-form-item label="拍摄人" prop="centre_uid">
                <el-select v-model="addVideoSzForm.centre_uid" multiple collapse-tags filterable placeholder="拍摄人" filterable style="width:100%">
                    <el-option :label="item.nickname" :value="item.id" v-for="item in photoSzList" :key="item.id"></el-option>
                </el-select>
            </el-form-item> -->
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="PrevFn('addVideoSzRef')" size="small" class="el-button-width">上一步</el-button>
            <el-button type="primary" @click="submitForm('addVideoSzRef')" size="small" :disabled='disabled' :loading="disabled" class="el-button-width">完成</el-button>
        </span>
    </el-dialog>
</template>

<script>
import { clientInfo,clientTos,tosLink } from "../../../assets/js/oss";
export default {
    name: "",
    data() {
        return {
            upload_disabled: false,
            disabled: false,
            disVideo: false,
            dialogVisible: false,
            progress_val: 0,
            is_change: 0,
            videoUrl: "",
            addVideoSzForm: {
                id: "",
                material: [],
            },
            PrevData:{}
        };
    },

    created() {
        this.$bus.on("addVideoSz", (value,data) => {
            console.log(value,data,'123123213')
            this.PrevData = data;
            this.addVideoSzForm.id = value.id;
            if (value.affected_rows == 0) {
                this.videoUrl = value.material;
            } else {
                this.videoUrl = "";
            }
            this.dialogVisible = value.dialogVsb;
        });
    },
    beforeDestroy() {
        this.$bus.off("addVideoSz");
    },
    methods: {
        // 视频上传格式验证
        beforeVideoUpload(file) {
            var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
            const extension = testmsg === "MP4" || testmsg === "mp4";
            const isLt2M = file.size / 1024 / 1024 < 100;
            if (!extension) {
                this.$message({
                    message: "上传视频只能是mp4 / MP4格式!",
                    type: "error",
                });
                return false;
            }
            if (!isLt2M) {
                this.$message({
                    message: "上传文件大小不能超过 100MB!",
                    type: "error",
                });
                return false;
            }
            return extension || isLt2M;
        },

        // 视频上传到oss
        async videoUploadRequest(option) {
            let that = this;
            let videoSrc = URL.createObjectURL(option.file);
            let videoElement = document.createElement("video");
            videoElement.src = videoSrc;
            videoElement.addEventListener("loadedmetadata", async (v)=> {
                URL.revokeObjectURL(videoSrc);
                let sizeVal =
                    videoElement.videoWidth / videoElement.videoHeight ==
                        16 / 9 ||
                    videoElement.videoWidth / videoElement.videoHeight ==
                        9 / 16;
                if (!sizeVal) {
                    that.$message.error("视频尺寸比例不正确");
                    return;
                }
                this.upload_disabled = true;
                const { data: res } = await this.$http.post(
                    "adminapi/Demandszv2/videoUploadName",
                    {
                        id: this.addVideoSzForm.id,
                    }
                );
                if (res.code !== 200) {
                    this.upload_disabled = false;
                    this.$message.error(res.msg);
                    return;
                } else {
                    this.upload_disabled = false;
                    var testmsg = option.file.name.substring(
                        option.file.name.lastIndexOf(".")
                    );
                    var fileName = res.data.material_name + testmsg;
                    this.disVideo = true;
                    const that = this;
                    try {
                        const client = clientInfo;
                        const clienttos = clientTos
                        let file = option.file;
                        let nowData = new Date();
                        let year = nowData.getFullYear();
                        let month =
                            nowData.getMonth() + 1 < 10
                                ? "0" + (nowData.getMonth() + 1)
                                : nowData.getMonth() + 1;
                        let date =
                            nowData.getDate() < 10
                                ? "0" + nowData.getDate()
                                : nowData.getDate();
                        let getData = year + "-" + month + "-" + date;
                        let relativePath = "source4.0/" + getData + "/";
                        const ret = await clienttos.putObject({
                            key: relativePath + fileName,
                            body: file,
                            progress: (p, cpt) => {
                                that.progress_val = Math.floor(p * 100);
                            },
                        });
                        if (ret.statusCode === 200) {
                            let url = tosLink+relativePath + encodeURIComponent(fileName)
                            let urlstr = url.substring(0, url.lastIndexOf("?"));
                            var timestamp = new Date().getTime();
                            this.videoUrl = url + "?v=" + timestamp;
                            this.addVideoSzForm.material.push({
                                url: url + "?v=" + timestamp,
                                name: fileName,
                            });
                            this.$message({
                                message: "上传成功！",
                                type: "success",
                            });
                            this.progress_val = 0;
                            this.is_change = 1;
                            this.disVideo = false;
                        } else {
                            this.progress_val = 0;
                            this.is_change = 0;
                            this.$message.error("上传失败！");
                            this.disVideo = false;
                        }
                        // let ret = await client.multipartUpload(
                        //     relativePath + fileName,
                        //     file,
                        //     {
                        //         progress: function (p) {
                        //             that.progress_val = Math.floor(p * 100);
                        //         },
                        //     }
                        // );
                        // if (ret.res.statusCode === 200) {
                        //     let url = ret.res.requestUrls[0];
                        //     let urlstr = url.substring(0, url.lastIndexOf("?"));
                        //     var timestamp = new Date().getTime();
                        //     this.videoUrl = urlstr + "?v=" + timestamp;
                        //     this.addVideoSzForm.material.push({
                        //         url: urlstr + "?v=" + timestamp,
                        //         name: fileName,
                        //     });
                        //     this.$message({
                        //         message: "上传成功！",
                        //         type: "success",
                        //     });
                        //     this.progress_val = 0;
                        //     this.is_change = 1;
                        //     this.disVideo = false;
                        // } else {
                        //     this.progress_val = 0;
                        //     this.is_change = 0;
                        //     this.$message.error("上传失败！");
                        //     this.disVideo = false;
                        // }
                    } catch (error) {
                        this.progress_val = 0;
                        this.is_change = 0;
                        this.$message.error("上传失败！");
                        this.disVideo = false;
                    }
                }
            });
        },

        // 提交添加
        submitForm(formName) {
            if (this.is_change == 0) {
                this.resetForm(formName);
            } else {
                this.$refs[formName].validate(async (valid) => {
                    if (valid) {
                        this.disabled = true;
                        const { data: res } = await this.$http.post(
                            "adminapi/Demandszv2/videoUpload",
                            this.addVideoSzForm
                        );
                        if (res.code !== 200) {
                            this.disabled = false;
                            this.$message.error(res.msg);
                            return;
                        } else {
                            this.$message({
                                message: "上传成功",
                                type: "success",
                            });
                            this.disabled = false;
                            this.resetForm(formName);
                            this.$parent.getDataList(this.$parent.queryInfo.page);
                        }
                    } else {
                        this.disabled = false;
                        return false;
                    }
                });
            }
        },

        // 视频删除
        deletVideo() {
            this.videoUrl = "";
            this.is_change = 0;
            this.addVideoSzForm.material = [];
        },
        //上一步
        PrevFn(name){
            this.$parent.eidtVideoSz(this.PrevData);
            this.resetForm(name)
        },
        // 关闭重置表单
        resetForm(formName) {
            
            this.$refs[formName].resetFields();
            this.videoUrl = "";
            this.addVideoSzForm.material = [];
            this.is_change = 0;
            this.dialogVisible = false;
        },
    },
};
</script>
<style scoped>
>>> .upload_dia .el-form{
    padding: 20px;
    border-bottom: 1px solid #E8EAEC;
}
>>> .upload_dia .el-dialog__body{
    padding: 0 !important;
}
.up_header{
    font-size: 16px;
    color: #191B1E;
    width: 100%;
    padding:12px 0;
    justify-content: center;
    align-items: center;
    background: #F8F8F9;
}
.up_header div:nth-child(1){
    margin-right: 12px;
}
.up_header div:nth-child(3){
    width: 100px;
    height: 2px;
    margin: 0 40px;
    background: #D7DADE;
}
.up_header div:nth-child(4){
    margin-right: 12px;
    border-radius: 32.5px;
    background: #165DFF;
    color: #FFF;
    padding: 1px 5px;
    font-size: 13px;
}
.pot_content {
    width: 100%;
    height: 181px;
    background-color: rgba(165, 177, 209, 0.08);
    border-radius: 12px;
    flex-direction: column;
    justify-content: center;
}
.pot_text {
    font-size: 13px;
    color: #25282c;
    line-height: 18px;
    margin-top: 12px;
}
.pot_tips {
    font-size: 13px;
    color: #828b99;
    margin-top: 4px;
    line-height: 18px;
}
.video_box {
    width: 109px;
    height: 181px;
    margin: 0 auto;
    position: relative;
}
.video_box::after {
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 1;
    background-color: rgba(0, 0, 0, 0.2);
    top: 0;
    left: 0;
    display: none;
}
.delet_icon {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    padding: 4px;
    cursor: pointer;
    display: none;
    z-index: 2;
}
.video_box:hover .delet_icon,
.video_box:hover::after {
    display: block;
}
</style>
<style>
.load-uploader {
    width: 100%;
    height: 183px;
}
.load-uploader .el-upload {
    display: block;
}
.load-uploader .el-upload-dragger {
    width: 100%;
    height: 183px;
    border: 0;
}
</style>
